import Vue from 'vue'
import axios from 'axios'
import store from '@/store'

import { getAccessToken } from '@/utils/auth'

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    timeout: 500000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
    config => {
        // do something before request is sent
        config.headers['accessToken'] = getAccessToken()
        return config
    },
    error => {
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    response => {
        const res = response.data
        if (!!res && res.success) {// 请求接口成功
            return res
        } else {// 请求接口失败
            // alert("请求错误："+res.message)
            // Vue.prototype.$layer.open({
            //     icon: 1,
            //     title: '请求失败',
            //     content: "<span style='color:red;line-height: 45px;'>"+ res.message +"</span>",
            // });

            Vue.prototype.$Modal.warning({
                title: '请求失败',
                content: res.message,
            });

            return Promise.reject(new Error(res.message || 'Error'))
        }
    },
    error => {
        console.log('err: ' + error) // for debug
        /*Vue.prototype.$layer.open({
            icon: 1,
            title: '服务器异常',
            content: "<span style='color:red;line-height: 45px;'>"+ error +"</span>",
        });*/

        Vue.prototype.$Modal.warning({
            title: '服务器异常',
            content: error
        });

        return Promise.reject(error)
    }
)

export default service
